package com.browan.demo;

import java.util.HashSet;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import com.browan.demo.http.MeetingApi;
import com.browan.demo.http.MeetingReturned;
import com.browan.freeppmobile.jni.FreeppKit;

public class ContactActivity extends Activity {

	private MeetingApi mMeetingApi;
	private ListView mContactList = null;
	private Button mStartButton = null;

	private ArrayAdapter<String> mAdapter = null;
	private String[] mContacts = null;
	
	private ProgressDialog mWaitDialog = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contact);
		mContactList = (ListView) findViewById(R.id.contact_list);
		mStartButton = (Button) findViewById(R.id.start_btn);

		mMeetingApi = MeetingApi.getInstance();

		FreeppKit.getInstance().setContext(this);
		FreeppKit.getInstance().loadAccount();

		if (!hasRegistered()) {
			Intent reg = new Intent(this, RegisterDialog.class);
			this.startActivityForResult(reg, 1);
		} else {
			Intent service = new Intent(this, DaemonService.class);
			this.startService(service);

			if(FreeppKit.inMeeting) {
				Intent meeting = new Intent(this, MeetingActivity.class);
				startActivity(meeting);
			}
			else {
				updateList();
			}
		}

		mStartButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				long[] ids = mContactList.getCheckItemIds();
				if (ids.length > 0) {
					FreeppKit.getInstance().meetingMembers.clear();
					
					StringBuffer buf = new StringBuffer();
					for (int i = 0; i < ids.length; i++) {
						String number = mAdapter.getItem((int)ids[i]);
						FreeppKit.getInstance().meetingMembers.put(number, false);
						buf.append(number).append(",");
					}
					buf.deleteCharAt(buf.length() - 1);

					MeetingApi.getInstance().startMeeting(FreeppKit.e164Number,
							buf.toString());
					
					FreeppKit.needRingback = true;
					showWaitingDialog();
				}
			}

		});
	}
	
	private void showWaitingDialog() {
		mWaitDialog = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER);
		mWaitDialog.setTitle("开始会议");
		mWaitDialog.setMessage("会议室准备中，请稍候...");
		mWaitDialog.setCancelable(false);
		mWaitDialog.show();
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		FreeppKit.needRingback = false;
	}

	@Override
	protected void onStop() {
		super.onStart();
		if(mWaitDialog != null) mWaitDialog.cancel();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == 1) {
			Intent service = new Intent(this, DaemonService.class);
			startService(service);
			
			updateList();
		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("注册失败").setMessage("无法注册此号码，请更换号码，检查网络，稍后再试。");
			builder.setCancelable(false);
			builder.setNeutralButton("确定", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Intent reg = new Intent(ContactActivity.this, RegisterDialog.class);
					ContactActivity.this.startActivityForResult(reg, 1);
				}
			});
			builder.show();
		}
	}

	private void updateList() {
		MeetingReturned returned = mMeetingApi.getFriends();
		if (returned != null && returned.members != null && returned.members.length > 0) {
			filterNumber(returned.members);

			mAdapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_multiple_choice,
					mContacts);
			mContactList.setItemsCanFocus(false);
			mContactList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
			mContactList.setAdapter(mAdapter);
		}
	}

	private void filterNumber(String[] src) {

		HashSet<String> set = new HashSet<String>();
		for (String str : src) {
			set.add(str);
		}

		set.remove(FreeppKit.e164Number);
		mContacts = new String[set.size()];

		int i = 0;
		for (String str : set) {
			mContacts[i] = str;
			i++;
		}
	}

	private boolean hasRegistered() {
		return (FreeppKit.freeppId != null) && (FreeppKit.e164Number != null);
	}

}